<template>
  <view class="container">
    <!-- 头像选择区域 -->
    <view class="avatar-section">
      <button 
        class="avatar-button" 
        open-type="chooseAvatar" 
        @chooseavatar="onChooseAvatar"
      >
        <image v-if="avatarUrl" :src="avatarUrl" mode="aspectFill" class="avatar"></image>
        <image v-else src="/static/logo.png" mode="aspectFill" class="avatar placeholder"></image>
      </button>
    </view>
    
    <!-- 昵称输入区域 -->
    <view class="nickname-section">
      <view class="label">昵称</view>
      <input 
        type="nickname" 
        placeholder="请输入昵称" 
        v-model="nickName" 
        @blur="onNicknameBlur"
        class="nickname-input"
      />
    </view>
    
    <!-- 确认按钮 -->
    <button 
      class="confirm-button" 
      @tap="handleSubmit" 
      :loading="loading"
    >
      确认
    </button>
  </view>
</template>

<script>
import { sendWechatLogin } from '@/api/login.js';

export default {
  data() {
    return {
      avatarUrl: '',
      nickName: '',
      loading: false
    };
  },
  methods: {
    // 处理头像选择
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail;
      if (avatarUrl) {
        this.avatarUrl = avatarUrl;
      } else {
        uni.showToast({ title: '选择头像失败，请重试', icon: 'none' });
      }
    },
    
    // 处理昵称输入框失焦
    onNicknameBlur() {
      // 保持原有功能，用于微信的安全监测
    },
    
    // 处理表单提交
    handleSubmit() {
      // 验证输入
      if (!this.avatarUrl) {
        uni.showToast({ title: '请选择头像', icon: 'none' });
        return;
      }
      
      if (!this.nickName) {
        uni.showToast({ title: '请输入昵称', icon: 'none' });
        return;
      }
      
      // 获取临时登录凭证 code
      this.loading = true;
      uni.login({
        success: (loginRes) => {
          const code = loginRes.code;
          
          // 确保code存在
          if (!code) {
            this.loading = false;
            uni.showToast({ title: '获取登录凭证失败', icon: 'none' });
            return;
          }
          
          // 发送登录信息到后端
          sendWechatLogin({
            code,
            nickName: this.nickName,
            avatarUrl: this.avatarUrl
          })
            .then(res => {
              if (res.code === 200) {
                // 保存token到本地
                uni.setStorageSync('token', res.data.token);
                
                // 设置用户信息到Vuex store
                this.$store.commit('SET_TOKEN', res.data.token);
                // 从后端返回的数据中提取用户信息
                const userInfo = res.data;
                this.$store.commit('SET_USER_INFO', userInfo);
                // 添加设置角色的代码
                this.$store.commit('SET_ROLE', res.data.role || 'USER');
                console.log('用户信息:', userInfo);
                
                
                uni.showToast({ title: '登录成功', icon: 'success' });
                setTimeout(() => {
                  try {
                    uni.switchTab({ url: '/pages/index/index' });
                  } catch (e) {
                    console.error('页面跳转失败:', e);
                  }
                }, 500);
              } else {
                uni.showToast({ title: res.msg || '登录失败', icon: 'none' });
              }
            })
            .catch(() => {
              uni.showToast({ title: '登录失败，请重试', icon: 'none' });
            })
            .finally(() => {
              this.loading = false;
            });
        },
        fail: () => {
          this.loading = false;
          uni.showToast({ title: '获取微信登录凭证失败', icon: 'none' });
        }
      });
    }
  }
};
</script>

<style scoped>
.container {
  padding: 40rpx;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #fff;
  box-sizing: border-box;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin: 40rpx 0 60rpx;
}

.avatar-button {
  width: 180rpx;
  height: 180rpx;
  border-radius: 50%;
  overflow: hidden;
  padding: 0;
  background-color: transparent;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.avatar.placeholder {
  opacity: 0.5;
}

.nickname-section {
  margin-bottom: 60rpx;
}

.label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.nickname-input {
  width: 100%;
  height: 88rpx;
  font-size: 32rpx;
  color: #333;
  border-bottom: 1rpx solid #eee;
  padding: 0;
  box-sizing: border-box;
}

.nickname-input::placeholder {
  color: #999;
  font-size: 32rpx;
}

.confirm-button {
  width: 100%;
  height: 92rpx;
  line-height: 92rpx;
  font-size: 32rpx;
  background-color: #07c160;
  color: #fff;
  border-radius: 46rpx;
  margin-top: 0;
  margin-bottom: 80rpx; /* 增加底部边距，确保按钮不会紧贴底部 */
}
</style>